#include "SearcherServer.h"

SearcherServer::SearcherServer(size_t threadNum,size_t queSize,const string & ip,
                               unsigned short port,KeyRecommander* pKeyRecommander,
                               WebPageSearcher* pWebPageSearcher,
                               LRUCache* pLRUCache)
:_pool(threadNum,queSize)
,_server(ip,port)
,_pKeyRecommander(pKeyRecommander)
,_pWebPageSearcher(pWebPageSearcher)
,_pLRUCache(pLRUCache)
{
    LogInfo("The search engine server is started successfully.");
}



SearcherServer::~SearcherServer(){
    LogInfo("The search engine server has been shut down.");
}

void SearcherServer::start(){
    _pool.start();   //先启动线程池,保证服务器的任务到来后能发送的子线程处理
    using namespace std::placeholders;
    _server.setAllCallback(std::bind(&SearcherServer::onNewConnectiion,this,_1),
                           std::bind(&SearcherServer::onMessage,this,_1),
                           std::bind(&SearcherServer::onClose,this,_1));   //设置三个半时间
    _server.start();    //启动服务器
}

void SearcherServer::stop(){
    _server.stop();
    _pool.stop();
}

void SearcherServer::onNewConnectiion(const TcpConnectionPtr &conn){
    cout << conn->toString() << "has connected!" << endl;
}

void SearcherServer::onMessage(const TcpConnectionPtr &conn){
    /* string msg = conn->receive(); */
    /* cout << ">>recv client msg = " << msg << endl; */
    //做业务逻辑的处理
    /* MyTask task(msg,conn); */
    train_t train;
    conn->recvTrain(train);
    cout << ">> recv client train " << endl;
    /* cout << "train.length =  " << train.length << endl; */
    /* cout << "train.type =  " << train.type << endl; */
    /* cout << "train.jsonObj =  " << train.jsonObj << endl; */
    
    MyTask task(train,conn,_pKeyRecommander,_pWebPageSearcher,_pLRUCache);
    _pool.addTask(std::bind(&MyTask::process,task));
    //...
}

void SearcherServer::onClose(const TcpConnectionPtr &conn){
    cout << conn->toString() << "has closed!" << endl;
}
